package com.hycc.base;

public class ManageThread {
    public static void main(String[] args) {
        SynContainer container = new SynContainer();

        new Productor(container).start();
        new Custom(container).start();
    }
}


//生产者
class Productor extends Thread{
    SynContainer container;

    public Productor(SynContainer container){
        this.container = container;
    }

    //生产
    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            System.out.println("生产了"+i+"产品");
            container.add(new Product(i));
        }
    }
}

//消费者
class Custom extends Thread{
    SynContainer container;

    public Custom(SynContainer container){
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            System.out.println("消费了第"+container.consume().id+"个产品");
        }
    }
}

//产品
class Product{
    int id;

    public Product(int id){
        this.id=id;
    }
}

//缓冲区
class SynContainer{
    //需要一个容器
    Product[] products=new Product[10];
    int count = 0;

    //生产者生产产品
    public synchronized void add(Product product){
        //如果容器满了，等待消费者消费
        if(count==products.length){
            //生产等待
            try{
                this.wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        //如果没有满，新加产品
        products[count]=product;
        count++;

        //通知消费者，可以消费了
        this.notifyAll();
    }

    //消费者消费产品
    public synchronized Product consume(){
        if(count==0){
            //消费者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        Product product = products[count];

        //通知生产者
        this.notifyAll();

        return product;
    }
}